//
//  KATPieceAnimationView.m
//  KATFramework
//
//  Created by Yi Yu on 2017/5/16.
//  Copyright © 2017年 KatApp. All rights reserved.
//

#import "KATPieceAnimationView.h"



@interface KATPieceAnimationView ()

//行数
@property(nonatomic,assign) int rows;

//列数
@property(nonatomic,assign) int columns;

//切片数组(动画按该数组顺序执行)
@property(nonatomic,retain) NSArray<NSNumber *> *pieces;

//切片宽(相对大图比例)
@property(nonatomic,assign) double pieceWidth;

//切片高(相对大图比例)
@property(nonatomic,assign) double pieceHeight;

//已经播放的次数
@property(nonatomic,assign) int playedTimes;

//当前帧
@property(nonatomic,assign) int currentFrame;

//系统刷屏动作
@property(nonatomic,copy) void (^pieceActions)(void);


@end



@implementation KATPieceAnimationView


//获取实例(简化构造方法)
+ (instancetype)animationWithImage:(UIImage *)image rows:(int)rows columns:(int)columns
{
    return [self animationWithImage:image rows:rows columns:columns count:rows*columns interval:1 andPlayTimes:0];
}


//获取实例
+ (instancetype)animationWithImage:(UIImage *)image rows:(int)rows columns:(int)columns count:(int)count interval:(int)interval andPlayTimes:(int)times
{
    NSMutableArray<NSNumber *> *array=[NSMutableArray arrayWithCapacity:rows*columns];
    
    for(int i=0;i<rows*columns && i<count;i++)
    {
        [array addObject:@(i)];
    }
    
    return [self animationWithImage:image rows:rows columns:columns pieces:array interval:interval andPlayTimes:times];
}


//获取实例
+ (instancetype)animationWithImage:(UIImage *)image rows:(int)rows columns:(int)columns pieces:(NSArray <NSNumber *> *)pieces interval:(int)interval andPlayTimes:(int)times
{
    return [self animationWithImage:image size:CGSizeZero rows:rows columns:columns pieces:pieces interval:interval andPlayTimes:times];
}


//获取实例
+ (instancetype)animationWithImage:(UIImage *)image size:(CGSize)size rows:(int)rows columns:(int)columns pieces:(NSArray<NSNumber *> *)pieces interval:(int)interval andPlayTimes:(int)times
{
    //参数检测
    if(!image || rows<=0 || columns<=0 || !pieces || pieces.count<=0 || interval<1)
    {
        return nil;
    }
    
    
    KATPieceAnimationView *anim=[[[self alloc] init] autorelease];
        
    anim.layer.contentsGravity=kCAGravityResizeAspect;//等价于contentMode=UIViewContentModeScaleAspectFit
    
    anim.contents=image;
    anim.rows=rows;
    anim.columns=columns;
    anim.playTimes=times;
    anim.pieceFrameInverval=interval;
    anim.pieces=pieces;
    
    //切片尺寸
    anim.pieceWidth=1.0/anim.columns;
    anim.pieceHeight=1.0/anim.rows;
    
    //计算尺寸
    if(size.width<=0 || size.height<=0)
    {
        anim.bounds=CGRectMake(0, 0, image.size.width/anim.columns/SCREEN_SCALE, image.size.height/anim.rows/SCREEN_SCALE);
    }
    else
    {
        anim.bounds=CGRectMake(0, 0, size.width, size.height);
    }
    
    anim.currentFrame=0;
    anim.playedTimes=0;
    anim.pieceActions=nil;
    anim.eventDelegate=nil;
    
    //显示首帧
    [anim displayPieceWithIndex:0];
    
    
    return anim;
}


//重新播放
- (void)replay
{
    _currentFrame=0;
    _playedTimes=0;
    
    [self play];
}


//播放（继续播放）
- (void)play
{
    if(!_pieceActions)
    {
        self.pieceActions=^(void)
        {
            [self displayPieceWithIndex:[_pieces[_currentFrame] intValue]];
            
            if(_currentFrame>=_pieces.count-1)//播放过头
            {
                _playedTimes++;
                
                if(_playTimes>0 && _playedTimes>=_playTimes)
                {
                    [self stop];
                    
                    //播放完成
                    if(_eventDelegate && [_eventDelegate respondsToSelector:@selector(pieceAnimationFinished:)])
                    {
                        [_eventDelegate pieceAnimationFinished:self];
                    }
                }
                else
                {
                    _currentFrame=0;
                }
            }
            else
            {
                _currentFrame++;
            }
            
        };
    }
    
    //未播放完成
    if(!self.displayLinkActionsRunning && (_playTimes<=0 || _playedTimes<_playTimes))
    {
        [self startDisplayLinkActions:_pieceActions withFrameInterval:_pieceFrameInverval];
    }
}


//停止
- (void)stop
{
    [self stopDisplayLinkActions];
}


//显示某一帧
- (void)displayPieceWithIndex:(int)index
{
    if(index>=0 && index<_columns*_rows)
    {
        //显示的范围
        CGRect rect=CGRectMake((index%_columns)*_pieceWidth, (index/_columns)*_pieceHeight, _pieceWidth, _pieceHeight);
        
        self.layer.contentsRect=rect;
    }
}


//释放内存
- (void)dealloc
{
    if(_pieceActions)
    {
        Block_release(_pieceActions);
        _pieceActions=nil;
    }
    
    [self stopDisplayLinkActions];
    
    [_pieces release];
    
    [super dealloc];
}


@end
